using AutoMapper;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.MaterialManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;
using RBAC.Read.Api.Application.Dto.ERP;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 物料分页列表 处理器
    /// </summary>
    public class GetMaterPageHandler : IRequestHandler<GetMaterPageCommand, APIPaging<MaterListDto>>
    {
        private readonly IBaseRepository<Mater> materRepository;
        private readonly IBaseRepository<MaterType> materTypeRepository;
        private readonly ILogger<GetMaterPageHandler> logger;
        private readonly IMapper mapper;

        public GetMaterPageHandler(
            IBaseRepository<Mater> materRepository,
            IBaseRepository<MaterType> materTypeRepository,
            ILogger<GetMaterPageHandler> logger,
            IMapper mapper)
        {
            this.materRepository = materRepository;
            this.materTypeRepository = materTypeRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        public Task<APIPaging<MaterListDto>> Handle(GetMaterPageCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<MaterListDto>();
            try
            {
                logger.LogInformation("开始获取物料分页列表 PageIndex={PageIndex}, PageSize={PageSize}", request.PageIndex, request.PageSize);

                // 如果传入了物料分类ID，则根据分类ID找到分类编码前缀
                if (request.MaterTypeId.HasValue && string.IsNullOrWhiteSpace(request.TypeCodePrefix))
                {
                    var type = materTypeRepository.GetModel(request.MaterTypeId.Value);
                    if (type != null && !string.IsNullOrWhiteSpace(type.TypeCode))
                    {
                        request.TypeCodePrefix = type.TypeCode;
                        logger.LogInformation("根据分类ID {MaterTypeId} 解析得到前缀 {TypeCodePrefix}", request.MaterTypeId, request.TypeCodePrefix);
                    }
                }

                var where = BuildWhereClause(request);
                var parameters = BuildParameters(request);

                var (data, total) = materRepository.GetPaged(request.PageIndex, request.PageSize, where, request.OrderBy, parameters);

                var dtoList = data.Select(m => new MaterListDto
                {
                    Id = m.Id,
                    MaterCode = m.MaterCode,
                    MaterName = m.MaterName,
                    ModelSpec = m.ModelSpec,
                    Unit = m.Unit,
                    SupplyMode = m.SupplyMode,
                    Status = m.Status
                }).ToList();

                result.Code = APIEnums.Success;
                result.PageDatas = dtoList;
                result.TotalCount = total;
                result.Msg = "获取物料列表成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取物料分页列表失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取物料列表失败";
                result.PageDatas = new List<MaterListDto>();
                result.TotalCount = 0;
            }

            return Task.FromResult(result);
        }

        private string BuildWhereClause(GetMaterPageCommand request)
        {
            var conditions = new List<string>();
            if (!string.IsNullOrWhiteSpace(request.MaterCode))
            {
                conditions.Add("MaterCode LIKE @MaterCode");
            }
            if (!string.IsNullOrWhiteSpace(request.MaterName))
            {
                conditions.Add("MaterName LIKE @MaterName");
            }
            // 若采用编码前缀与分类关联
            if (!string.IsNullOrWhiteSpace(request.TypeCodePrefix))
            {
                conditions.Add("MaterCode LIKE @TypeCodePrefix");
            }

            return conditions.Count > 0 ? string.Join(" AND ", conditions) : string.Empty;
        }

        private object BuildParameters(GetMaterPageCommand request)
        {
            var p = new Dictionary<string, object>();
            if (!string.IsNullOrWhiteSpace(request.MaterCode))
            {
                p["MaterCode"] = $"%{request.MaterCode}%";
            }
            if (!string.IsNullOrWhiteSpace(request.MaterName))
            {
                p["MaterName"] = $"%{request.MaterName}%";
            }
            if (!string.IsNullOrWhiteSpace(request.TypeCodePrefix))
            {
                // 前缀匹配
                p["TypeCodePrefix"] = $"{request.TypeCodePrefix}%";
            }
            return p;
        }
    }
}
